package com.oocl.MyHttpServer.runnable;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import com.oocl.MyHttpServer.controller.ServerController;
import com.oocl.MyHttpServer.controller.impl.ServerControllerImpl;

public class ServerRunnable implements Runnable {

	private Socket socket;

	ServerController controller;

	public ServerRunnable(Socket socket, ServerController controller) {
		this.socket = socket;
		this.controller = controller;
	}

	@Override
	public void run() {
		// /读 请求
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			String line = null;
			boolean isGet = false;
			while ((line = reader.readLine()).trim().length() != 0) {
				System.out.println(line);

				// /一般情况下
				if (line.startsWith("GET")) {
					System.out.println("Get 请求");
					isGet = true;
					this.controller.refresh(socket.getOutputStream());
					break;
				}
			}

			if (!isGet) {
				char[] buf = new char[30];
				int len = reader.read(buf);
				String body = new String(buf, 0, len);
				System.out.println(body);
				
				// /点击了启动按钮
				if(body.contains("open")){
					System.out.println("要打开聊天服务器");
					this.controller.turnOn(socket.getOutputStream());
				}
				
				// /点击了关闭按钮
				else if(body.contains("close")){
					System.out.println("要关闭聊天服务器");
					this.controller.turnOff(socket.getOutputStream());
				}
			}
			
			
			///最后要关闭socket
			System.out.println("socket最后关闭");
			reader.close();
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
